package org.example.road.learn01.handler;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
public class EchoHandler extends ChannelInboundHandlerAdapter {

    private AtomicInteger counter = new AtomicInteger();

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 连接成功后，发送1万条记录
        StringBuffer sb = new StringBuffer("hello server");
        for (int i = 0; i < 100; i++) {
            byte[] contents = sb.append(i).toString().getBytes(StandardCharsets.UTF_8);
            counter.getAndAdd(contents.length);
            ctx.flush().write(Unpooled.copiedBuffer(contents));
        }
        ctx.channel().flush();

        // 关闭连接
//        ctx.channel().close();
        // 传递给下一个处理器
        super.channelActive(ctx);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // super.channelRead(ctx, msg);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        // 连接关闭，打印发送了多少字节
        log.info("本连接发送字节数：{}", counter.get());
    }
}
